package grasshopper.utils;

import java.util.HashMap;
import java.util.Map;

/**
 *
 * @author piokob
 */
public class TextTools {

    private static final char[][] asciiReplacements = {
        {'ą', 'a'},
        {'ć', 'c'},
        {'ę', 'e'},
        {'ł', 'l'},
        {'ń', 'n'},
        {'ó', 'o'},
        {'ś', 's'},
        {'ż', 'z'},
        {'ź', 'z'},
        {'Ą', 'A'},
        {'Ć', 'C'},
        {'Ę', 'E'},
        {'Ł', 'L'},
        {'Ń', 'N'},
        {'Ó', 'O'},
        {'Ś', 'S'},
        {'Ż', 'Z'},
        {'Ź', 'Z'},
        {'å', 'a'},
        {'ä', 'a'},
        {'ö', 'o'},
        {'Å', 'A'},
        {'Ä', 'A'},
        {'Ö', 'O'}
    };
    private final static Map<Character, Character> asciiReplacementMap = new HashMap<Character, Character>();

    static {
        for (char[] cc : asciiReplacements) {
            asciiReplacementMap.put(cc[0], cc[1]);
        }
    }

    /**
     * Converts national charaters into mapped ascii chars. If input string is
     * null then null is returned.
     *
     * <p/>
     * unit test: TextToolsTest.convertToAsciiTest()
     * 
     * @param s input string
     * @return output string in ascii
     */
    public static String convertToAscii(String s) {
        if (s == null) {
            return null;
        }
        if (s.length() == 0) {
            return "";
        }
        StringBuilder sb = new StringBuilder(s.length());
        char[] chars = s.toCharArray();
        for (char c : chars) {
            if (c >= 0x0020 && c <= 0x007d || c == 0x000a || c == 0x000D) {
                sb.append(c);
            } else if (asciiReplacementMap.containsKey(c)) {
                sb.append(asciiReplacementMap.get(c));
            } else {
                sb.append("?");
            }
        }
        return sb.toString();
    }
}
